{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 可视化的链接文件下载\n",
    "- 默认下载路径：./static/download\n",
    "- 链接格式要求：以xxx.文件名结尾，结尾没有/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from flask import Flask, request, render_template, flash\n",
    "import requests\n",
    "from urllib.request import unquote\n",
    "import threading\n",
    "import sqlite3 # 导入sqlit3库\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def getrecords():\n",
    "    data_base=sqlite3.connect('database')\n",
    "    cursor=data_base.cursor()\n",
    "    cursor.execute('create table if not exists records(filename text,time text)')\n",
    "    data_base.commit()\n",
    "    cursor.execute('select * from records')\n",
    "    results=cursor.fetchall()\n",
    "    records=[]\n",
    "    for r in results:\n",
    "        records.append({\"filename\": list(r)[0], \"time\": list(r)[1]})\n",
    "    return records"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def split(text):# text最后不可以加‘/’，要以str输入\n",
    "    text = str(text)\n",
    "    stext = text.split(\"/\",-1)\n",
    "    # print(stext)\n",
    "    filename=stext[-1]\n",
    "    filename=unquote(filename, encoding='utf-8')#转码\n",
    "    return filename"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def download(path,url):\n",
    "    try:\n",
    "        print('正在下载...%s'%split(url))\n",
    "        r = requests.get(url,stream=True) \n",
    "        content_size = int(r.headers['content-length'])\n",
    "        print('总大小%.2fMb'%(content_size/1024/1024))\n",
    "        with open(\"%s/%s\"%(path,split(url)), \"wb\") as f:\n",
    "            n=0\n",
    "            for chunk in r.iter_content(chunk_size=1024*1024):\n",
    "                if chunk:\n",
    "                    loaded = n*1024*1024/content_size\n",
    "                    f.write(chunk)\n",
    "                    print('已下载%.2f%%...%s'%(loaded*100,split(url)))\n",
    "                    n=n+1\n",
    "        print('下载成功...%s'%split(url))\n",
    "        data_base=sqlite3.connect('database')\n",
    "        cursor=data_base.cursor()\n",
    "        cursor.execute('create table if not exists records(filename text,time text)')\n",
    "        data_base.commit()\n",
    "        cursor.execute('insert into records (filename,time) VALUES (\\\"%s\\\",\\\"%s\\\")'%(split(url),time.ctime()))\n",
    "        data_base.commit()\n",
    "        print('数据库提交成功...%s'%split(url))\n",
    "        return 1\n",
    "    except:\n",
    "        print('下载失败！')\n",
    "        return 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "app = Flask(__name__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "@app.route('/', methods=['GET', 'POST'])\n",
    "def index():\n",
    "    if request.method == 'GET':\n",
    "        records=getrecords()\n",
    "        return render_template('index.html',records=records)\n",
    "    else:#post方法\n",
    "        url = request.form.get('url')\n",
    "        url = str(url)\n",
    "        path='./static/download'\n",
    "        threading.Thread(target=download,args=(path,url)).start()#并行下载进程\n",
    "        return render_template('downloading.html')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " * Serving Flask app \"__main__\" (lazy loading)\n",
      " * Environment: production\n",
      "   WARNING: This is a development server. Do not use it in a production deployment.\n",
      "   Use a production WSGI server instead.\n",
      " * Debug mode: off\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      " * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)\n",
      "127.0.0.1 - - [18/Mar/2020 13:04:05] \"\u001b[37mGET / HTTP/1.1\u001b[0m\" 200 -\n"
     ]
    }
   ],
   "source": [
    "if __name__ == '__main__':\n",
    "    app.run(host='0.0.0.0',threaded=True,port=5000)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
